/**************************************************************************
 * @file     sys_uart.c
 * @version  V1.00
 * $Revision: 5 $
 * $Date: 15/05/18 4:02p $
 *****************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <stdlib.h>
#include "bsp_api.h"
#include "com_obj.h"
#include "os_obj.h"

#define PT_NEW_LINE 1 // 0-n , 1-\r\n , 2-\n\r
#define com_port com.obj01

/*******************************************************************************
 * @brief  __sys_put_ch
 * \param[in] none
 * \retval: none
 *******************************************************************************/
void __sys_put_ch(char ch)
{
#if PT_NEW_LINE == 0
     com_port.fun->snd_byte(ch);
#elif PT_NEW_LINE == 1
    if (ch != '\n')
    {
        com_port.fun->snd_byte(ch);
    }
    else
    {
        com_port.fun->snd_byte('\r');
        com_port.fun->snd_byte('\n');
    }
#elif PT_NEW_LINE == 2
    if (ch != '\n')
    {
        com_port.fun->snd_byte(ch);
    }
    else
    {
        com_port.fun->snd_byte('\n');
        com_port.fun->snd_byte('\r');
    }
#endif
}

/*******************************************************************************
 * @brief  sys_hw_console_output
 * \param[in] str : string to print
 * \retval: none
 *******************************************************************************/
void sys_hw_console_output(const char *str)
{
    /* empty console output */
    while (*str)
    {
        __sys_put_ch(*str++);
    }
}

void rt_hw_console_output(const char *str)
{
    if (com_port.fun)
    {
        while (*str)
        {
            com_port.fun->hal_send(*str++);
        }
    }
}

/*******************************************************************************
 * @brief  sys_hw_puts
 * \param[in]  str : string to print
 * \retval: none
 *******************************************************************************/
void sys_hw_puts(const char *str)
{
    osMutexWait(os_obj.mid_printf, 1000);

    sys_hw_console_output(str);

    osMutexRelease(os_obj.mid_printf);
}

/*******************************************************************************
 * @brief  sys_hw_printf
 * \param[in] fmt: format var like printf
 * \retval: none
 *******************************************************************************/
static char buf_str[240 + 1];
void sys_hw_printf(char *fmt, ...)
{
    va_list v_args;

    osMutexWait(os_obj.mid_printf, 1000);

    va_start(v_args, fmt);
    (void)vsnprintf((char *)&buf_str[0],
                    (size_t)sizeof(buf_str) - 5,
                    (char const *)fmt,
                    v_args);
    va_end(v_args);

    sys_hw_console_output(buf_str);

    osMutexRelease(os_obj.mid_printf);
}
